//
//  BubbleView.m
//  SpringbackBubble
//
//  Created by TOPTEAM on 2016/11/24.
//  Copyright © 2016年 TOPTEAM. All rights reserved.
//

#import "BubbleView.h"
@interface BubbleView ()

@property (nonatomic,assign) CGPoint point_begin; //起始的中心点
@property (nonatomic,assign) CGPoint point_oldBackViewCenter;
@property (nonatomic,strong) UIView *view_R1;
@property (nonatomic,strong) CAShapeLayer *shapeLayer;

@end

@implementation BubbleView{
    
    UIBezierPath *bezierPath;
    UIColor *fillColorForCute;//A->O->D->C->P->B-A  勾画的贝塞尔曲线填充颜色
    UIDynamicAnimator *animator;
    UISnapBehavior  *snap;
    
    CGFloat r1;//起始圈半径r1
    CGFloat r2;//手指一动圈半径r2
    
    CGFloat x1;//起始圈center的x坐标
    CGFloat y1;//起始圈center的y坐标
    
    CGFloat x2;//手指一动圈center的x坐标
    CGFloat y2;//手指一动圈center的y坐标
    
    CGFloat d_R1_R2;//两个圆心之间的距离
    
    CGFloat _cosθ;
    CGFloat _sinθ;
    
    CGPoint point_A; //A
    CGPoint point_B; //B
    CGPoint point_C; //C
    CGPoint point_D; //D
    
    CGPoint point_O; //O
    CGPoint point_P; //P
    
    CGRect oldBackViewFrame;
    
}

-(id)initWithBeginPoint:(CGPoint)point superView:(UIView *)view{
    self = [super initWithFrame:CGRectMake(point.x, point.y, self.bubbleWidth, self.bubbleWidth)];
    if(self){
        _point_begin = point;
        self.superView = view;
        [self.superView addSubview:self];
        self.viscosity  = 20;
        self.bubbleWidth = 50;
        self.bubbleColor = [UIColor colorWithRed:0 green:0.722 blue:1 alpha:1];
        [self draw];
    }
    return self;
}

-(void)draw{
    
    _shapeLayer = [CAShapeLayer layer];
    self.backgroundColor = [UIColor clearColor];
    /*
     * 创建frontView--手指拖动时的圆
     */
    self.view_R2 = [[UIView alloc]initWithFrame:CGRectMake(_point_begin.x,_point_begin.y, self.bubbleWidth, self.bubbleWidth)];
    /*
     * 手指拖动圈的半径
     */
    r2 = self.view_R2.bounds.size.width / 2;
    
    
    _view_R2.layer.cornerRadius = r2;
    
    _view_R2.backgroundColor = self.bubbleColor;
    
    
    /*
     * backView
     */
    _view_R1 = [[UIView alloc]initWithFrame:self.view_R2.frame];
    
    /*
     * 起始位置圈的半径
     */
    r1 = _view_R1.bounds.size.width / 2;
    
    
    _view_R1.layer.cornerRadius = r1;
    
    
    
    _view_R1.backgroundColor = self.bubbleColor;
    
    self.imgV =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ball"]];
    self.imgV.frame = CGRectMake(0, 0, self.view_R2.bounds.size.width, self.view_R2.bounds.size.height);
    [self.view_R2 insertSubview:self.imgV atIndex:0];
    
    [self.superView addSubview:_view_R1];
    [self.superView addSubview:_view_R2];
    
    
    
    
    
    
    x1 = _view_R1.center.x;
    y1 = _view_R1.center.y;
    x2 = self.view_R2.center.x;
    y2 = self.view_R2.center.y;
    
    point_A = CGPointMake(x1-r1, y1);    // A
    point_B = CGPointMake(x1+r1, y1);    // B
    point_D = CGPointMake(x2-r2, y2);    // D
    point_C = CGPointMake(x2+r2, y2);    // C
    point_O = CGPointMake(x1-r1, y1);    // O
    point_P = CGPointMake(x2+r2, y2);    // P
    
    oldBackViewFrame  = _view_R1.frame;
    _point_oldBackViewCenter = _view_R1.center;
    
    
    /*
     * 为了看到 frontView 的气泡晃动效果，需要暂时隐藏 backView
     */
    _view_R1.hidden = YES;
    
    [self addAniamtion_AS_GameCenterBubble];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handleDragGesture:)];
    [self.view_R2 addGestureRecognizer:pan];
    
}


-(void)drawRect{
    
    x1 = _view_R1.center.x;
    y1 = _view_R1.center.y;
    x2 = self.view_R2.center.x;
    y2 = self.view_R2.center.y;
    
    
    /*
     * 两个圆心之间的距离
     */
    d_R1_R2 = sqrtf((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
    
    
    
    
    
    if (d_R1_R2 == 0) {
        _cosθ = 1;
        _sinθ = 0;
    }else{
        _cosθ = (y2-y1)/d_R1_R2;
        _sinθ = (x2-x1)/d_R1_R2;
    }
    /*
     * 圆一的半径和手指移动距离有关   
     */
    r1 = oldBackViewFrame.size.width / 2 - d_R1_R2/self.viscosity;
    
    point_A = CGPointMake(x1-r1*_cosθ, y1+r1*_sinθ);  // A
    point_B = CGPointMake(x1+r1*_cosθ, y1-r1*_sinθ);  // B
    point_C = CGPointMake(x2+r2*_cosθ, y2-r2*_sinθ);  // C
    point_D = CGPointMake(x2-r2*_cosθ, y2+r2*_sinθ);  // D
    
    point_O = CGPointMake(point_A.x + (d_R1_R2 / 2)*_sinθ, point_A.y + (d_R1_R2 / 2)*_cosθ);
    point_P = CGPointMake(point_B.x + (d_R1_R2 / 2)*_sinθ, point_B.y + (d_R1_R2 / 2)*_cosθ);
    
    _view_R1.center = _point_oldBackViewCenter;
    _view_R1.bounds = CGRectMake(0, 0, r1*2, r1*2);
    _view_R1.layer.cornerRadius = r1;
    
    /*
     * A->O->D->C->P->B-A
     */
    bezierPath = [UIBezierPath bezierPath];
    [bezierPath moveToPoint:point_A];
    [bezierPath addQuadCurveToPoint:point_D controlPoint:point_O];
    [bezierPath addLineToPoint:point_C];
    [bezierPath addQuadCurveToPoint:point_B controlPoint:point_P];
    [bezierPath moveToPoint:point_A];
    
    if (_view_R1.hidden == NO) {
        _shapeLayer.path = [bezierPath CGPath];
        _shapeLayer.fillColor = [fillColorForCute CGColor];
        /*
         * //将一个子layer插入到最下面
         - (void)insertSublayer:(CALayer。。。。 *)layer below:(nullable CALayer *)sibling;
         */
        [self.superView.layer insertSublayer:_shapeLayer below:self.view_R2.layer];
    }
    
}


-(void)handleDragGesture:(UIPanGestureRecognizer *)ges{
    CGPoint dragPoint = [ges locationInView:self.superView];
    
    if (ges.state == UIGestureRecognizerStateBegan) {
        _view_R1.hidden = NO;
        fillColorForCute = self.bubbleColor;
        [self RemoveAniamtionLikeGameCenterBubble];
    }else if (ges.state == UIGestureRecognizerStateChanged){
        self.view_R2.center = dragPoint;
        if (r1 <= 6) {
            fillColorForCute = [UIColor clearColor];
            _view_R1.hidden = YES;
            [_shapeLayer removeFromSuperlayer];
        }
        [self drawRect];
    } else if (ges.state == UIGestureRecognizerStateEnded || ges.state ==UIGestureRecognizerStateCancelled || ges.state == UIGestureRecognizerStateFailed){
        
        _view_R1.hidden = YES;
        fillColorForCute = [UIColor clearColor];
        [_shapeLayer removeFromSuperlayer];
        [UIView animateWithDuration:0.5 delay:0.0f usingSpringWithDamping:0.4f initialSpringVelocity:0.0f options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.view_R2.center = _point_oldBackViewCenter;
        } completion:^(BOOL finished) {
            if (finished) {
                [self addAniamtion_AS_GameCenterBubble];
            }
        }];
    }
    
}



-(void)addAniamtion_AS_GameCenterBubble {
    
    CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    pathAnimation.calculationMode = kCAAnimationPaced;
    pathAnimation.fillMode = kCAFillModeForwards;
    pathAnimation.removedOnCompletion = NO;
    pathAnimation.repeatCount = INFINITY;
    pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    pathAnimation.duration = 5.0;
    
    CGMutablePathRef curvedPath = CGPathCreateMutable();
    CGRect circleContainer = CGRectInset(self.view_R2.frame, self.view_R2.bounds.size.width / 2 - 3, self.view_R2.bounds.size.width / 2 - 3);
    CGPathAddEllipseInRect(curvedPath, NULL, circleContainer);
    
    pathAnimation.path = curvedPath;
    CGPathRelease(curvedPath);
    [self.view_R2.layer addAnimation:pathAnimation forKey:@"myCircleAnimation"];
    
    CAKeyframeAnimation *scaleX = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale.x"];
    scaleX.duration = 1;
    scaleX.values = @[@1.0, @1.5, @1.0];
    scaleX.keyTimes = @[@0.0, @0.5, @1.0];
    scaleX.repeatCount = INFINITY;
    scaleX.autoreverses = YES;
    
    scaleX.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [self.view_R2.layer addAnimation:scaleX forKey:@"scaleXAnimation"];
    
    
    CAKeyframeAnimation *scaleY = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale.y"];
    scaleY.duration = 1.5;
    scaleY.values = @[@1.0, @1.5, @1.0];
    scaleY.keyTimes = @[@0.0, @0.5, @1.0];
    scaleY.repeatCount = INFINITY;
    scaleY.autoreverses = YES;
    scaleY.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [self.view_R2.layer addAnimation:scaleY forKey:@"scaleYAnimation"];
}

-(void)RemoveAniamtionLikeGameCenterBubble {
    [self.view_R2.layer removeAllAnimations];
}

@end






























































